package cn.kgc.vue.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.service.MailService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 课工场
 * @date 2024/9/26
 * @description
 */
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String account;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult sendMessage(String to) {

        // 创建邮件对象
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 设置发件人
        simpleMailMessage.setFrom(account);
        // 设置收件人
        simpleMailMessage.setTo(to);
        // 设置邮件主题
        simpleMailMessage.setSubject("数智教育平台,邮箱绑定验证");
        // 设置邮件发送时间
        simpleMailMessage.setSentDate(new Date());

        // 设置邮件内容
        int randomCode = RandomUtil.randomInt(100000, 999999);
        stringRedisTemplate.opsForValue().set(to,randomCode+"",3, TimeUnit.MINUTES);

        simpleMailMessage.setText("数智教育平台邮箱绑定验证码是:"+randomCode+",3分钟有效...");

        // 发送邮件
        mailSender.send(simpleMailMessage);

        return ResponseResult.success().message("验证码已发送");
    }
}
